#region Using

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;

using Gizmox.WebGUI.Common;
using Gizmox.WebGUI.Forms;
using Agresso.Interface.Layer.Domain;
using Agresso.Interface.Layer.Service;
using System.Collections;

#endregion

namespace Agresso.Interface.Layer.Web
{
    public partial class RoleMasterForm : Form
    {
        RoleMaster m_roleMaster;
        User m_current_user;
        EditMode m_editmode;
        UserService m_userService;
        MainForm m_mainForm;
        UserControlManageUserRole m_parentForm;

        public RoleMasterForm(string name, RoleMaster user, User currentUser, MainForm mainForm, UserControlManageUserRole parentForm, EditMode editmode)
        {
            InitializeComponent();
            m_roleMaster = user;
            m_current_user = currentUser;
            m_mainForm = mainForm;
            this.Name = name;
            m_parentForm = parentForm;
            m_userService = (UserService)ServiceFactory.Instance().GetService(ServiceFactory.USERSERVICE);
            initButtonEvent();
            if (user.RoleMasterID == 0)
            {
                clearForm();
            }
            else
            {
                loadRoleMaster();
                enableForm(editmode == EditMode.Edit);
            }
            setEditMode(editmode);
            //enableForm(false);
            
        }

        void toolBarButtonEdit_Click(object sender, EventArgs e)
        {
            setEditMode(EditMode.Edit);
            enableForm(!toolBarButtonEdit.Enabled);
        }

        private void enableForm(bool enable)
        {
            textBoxRoleMasterName.ReadOnly = !enable;
            dataGridViewCheckBoxColumnNew.ReadOnly = !enable;
            dataGridViewCheckBoxColumnUpdate.ReadOnly = !enable;
            dataGridViewCheckBoxColumnView.ReadOnly = !enable;
            dataGridViewCheckBoxColumnDelete.ReadOnly = !enable;
        }

        void toolBarButtonCancel_Click(object sender, EventArgs e)
        {
            if (m_editmode == EditMode.Load)
                this.Close();
            else
                MessageBox.Show("Are you sure to cancel?", "Confirmation", MessageBoxButtons.YesNo,
                   MessageBoxIcon.Question, new EventHandler(cancelConfirmation));
        }

        void cancelConfirmation(object sender, EventArgs e)
        {
            MessageBoxWindow msg = (MessageBoxWindow)sender;
            if (msg.DialogResult == DialogResult.Yes)
            {
                this.Close();
            }
        }

        private void initButtonEvent()
        {
            //toolBarButtonClear.Click += new EventHandler(toolBarButtonClear_Click);
            toolBarButtonSave.Click += new EventHandler(toolBarButtonSave_Click);
            //toolBarButtonDelete.Click += new EventHandler(toolBarButtonDelete_Click);
            toolBarButtonRefresh.Click += new EventHandler(toolBarButtonRefresh_Click);
            toolBarButtonEdit.Click += new EventHandler(toolBarButtonEdit_Click);
            //toolBarButtonSearch.Click += new EventHandler(toolBarButtonSearch_Click);
            toolBarButtonCancel.Click += new EventHandler(toolBarButtonCancel_Click);
        }

        void toolBarButtonRefresh_Click(object sender, EventArgs e)
        {
            //loadAllUser();
            //initComboDataSource();
            if (m_editmode == EditMode.Load || m_editmode == EditMode.Edit)
                loadRoleMaster();
        }

        private void loadRoleMaster()
        {
            textBoxRoleMasterName.Text = m_roleMaster.RoleName;
            UpdateRoleDetails();
        }

        public void UpdateRoleDetails()
        {
            dataGridViewRule.Rows.Clear();
            foreach (string key in m_roleMaster.RoleDetails.Keys)
            {
                RoleDetail rule = (RoleDetail)m_roleMaster.RoleDetails[key];
                DataGridViewRow rw = dataGridViewRule.Rows[dataGridViewRule.Rows.Add(rule.FormName, rule.ViewFlag, rule.NewFlag, rule.UpdateFlag, rule.DeleteFlag)];
                rw.Tag = rule;
            }
            IList forms = UserControlFactory.GetFormNames();
            //check for missing form---------
            foreach (string formname in forms)
            {
                if (!m_roleMaster.RoleDetails.ContainsKey(formname))
                {
                    RoleDetail rule = new RoleDetail(formname);
                    m_roleMaster.AddRoleDetails(rule);
                    DataGridViewRow rw = dataGridViewRule.Rows[dataGridViewRule.Rows.Add(rule.FormName, rule.ViewFlag, rule.NewFlag, rule.UpdateFlag, rule.DeleteFlag)];
                    rw.Tag = rule;
                }
            }
            //-------------------------------
        }

        private bool isValidForm()
        {
            clearErrorProvider();
            bool valid_a = textBoxRoleMasterName.Text != string.Empty;
            if (!valid_a) errorProviderRoleMaster.SetError(textBoxRoleMasterName, "Role Master Name can not be empty");
            return valid_a;//&& valid_b && valid_c && valid_d;
        }

        private void clearErrorProvider()
        {
            errorProviderRoleMaster.SetError(textBoxRoleMasterName, "");
        }

        private void addRoleDetails()
        {
            m_roleMaster.RoleDetails.Clear();
            foreach (DataGridViewRow rw in dataGridViewRule.Rows)
            {
                if (rw.Tag == null) continue;
                RoleDetail rule = (RoleDetail)rw.Tag;
                rule.ViewFlag = Convert.ToBoolean(dataGridViewRule[1, rw.Index].Value);
                rule.NewFlag = Convert.ToBoolean(dataGridViewRule[2, rw.Index].Value);
                rule.UpdateFlag = Convert.ToBoolean(dataGridViewRule[3, rw.Index].Value);
                rule.DeleteFlag = Convert.ToBoolean(dataGridViewRule[4, rw.Index].Value);
                m_roleMaster.AddRoleDetails(rule);
            }
        }

        private void setEditMode(EditMode editMode)
        {
            toolBarButtonSave.Enabled = (editMode == EditMode.Create || editMode == EditMode.Edit || editMode == EditMode.Saved || editMode == EditMode.Delete) && m_current_user.AdminAccess;//RoleDetails(this.Name).NewFlag;
            // toolBarButtonDelete.Enabled = (editMode == EditMode.Loaded) && m_current_user.RoleDetails(this.Name).DeleteFlag;
            toolBarButtonEdit.Enabled = (editMode == EditMode.Load) && m_current_user.AdminAccess;//RoleDetails(this.Name).UpdateFlag;
            //toolBarButtonClear.Enabled = m_current_user.RoleDetails(this.Name).UpdateFlag;
            m_editmode = editMode;
            labelEditMode.Text = "[" + editMode + "]";
        }

        void toolBarButtonSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (isValidForm())
                {
                    m_roleMaster.RoleName = textBoxRoleMasterName.Text;
                    addRoleDetails();
                    m_roleMaster.CreatenBy = m_current_user.UserID;
                    m_roleMaster.ModificationBy = m_current_user.UserID;
                    if (m_roleMaster.RoleMasterID > 0)
                    {
                        m_userService.UpdateRoleMaster(m_roleMaster);
                    }
                    else
                    {
                        m_userService.InsertRoleMaster(m_roleMaster);
                    }
                    //if (m_roleMaster.RoleMasterID == m_current_user.Role.RoleMasterID)
                    //{
                    //    m_current_user.Role = m_roleMaster;
                    //    m_mainForm.RefreshUserAndPermission(m_current_user);
                    //}
                    m_parentForm.LoadAllRoleMaster();
                    MessageBox.Show("Record has been saved", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information, new EventHandler(closeForm));
                    //clearForm();
                    //setEditMode(EditMode.Saved);
                }
            }
            catch (Exception x)
            {
                MessageBox.Show(x.Message, "Error Exception", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
            }

        }
        void closeForm(object sender, EventArgs e)
        {
            this.Close();
        }


        private void clearForm()
        {
            textBoxRoleMasterName.Text = string.Empty;
            //textBoxUserCode.Text = string.Empty;
            //textBoxPassword.Text = string.Empty;
            //textBoxConfirmPassword.Text = string.Empty;
            //textBoxEmail.Text = string.Empty;
            //dateTimePickerExpiry.Value = DateTime.Today.AddMonths(3);
            textBoxRoleMasterName.SelectAll();
            m_roleMaster = new RoleMaster();
            foreach (string name in UserControlFactory.GetFormNames())
            {
                RoleDetail rl = new RoleDetail(name);
                m_roleMaster.AddRoleDetails(rl);
            }
            UpdateRoleDetails();
            //listViewRecords.SelectedItems.Clear();
            enableForm(true);
            setEditMode(EditMode.Create);
        }
    }
}